package scau.zhong.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import scau.zhong.common.user.UserServiceException;
import scau.zhong.pojo.Permission;
import scau.zhong.pojo.Role;
import scau.zhong.pojo.User;
import scau.zhong.service.Impl.UserService;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 查询所有，包括角色列表
     * @return
     */
    @RequestMapping("/all")
    public ResponseEntity<List<User>> findAll(){
        return ResponseEntity.ok(userService.findAll());
    }

    /**
     * 根据用户ID查询角色
     * @param id
     * @return
     */
    @RequestMapping("/roles/{id}")
    public ResponseEntity<List<Role>> queryRoles(@PathVariable("id")String id){
        return ResponseEntity.ok(userService.queryRoleById(id));
    }

    /**
     * 根据用户ID查询权限
     * @param id
     * @return
     */
    @RequestMapping("/permissions/{id}")
    public ResponseEntity<List<Permission>> queryByPermissions(@PathVariable("id")String id){
        return ResponseEntity.ok(userService.queryPermissionByUID(id));
    }

    /**
     * 注册普通用户
     * @param user
     * @return
     * @throws UserServiceException
     */
    @PostMapping("/registry")
    public ResponseEntity<Void> registry(@RequestBody User user) throws UserServiceException {
        //检查该用户是否已经注册，判断依据为邮箱
        boolean exit = userService.isUserExit(user.getEmail());
        if(exit){
            throw new UserServiceException("该用户已存在");
        }
        if(user == null){
            return ResponseEntity.badRequest().build();
        }
        //加密密码
        user.setPassword(userService.encode(user.getPassword()));
        int flag = userService.insertUser(user);
        if(flag != 1){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 注册管理员用户
     * @param user
     * @return
     * @throws UserServiceException
     */
    @PostMapping("/adminRegistry")
    public ResponseEntity<Void> registryAdmin(@RequestBody User user) throws UserServiceException{
        //检查该用户是否已经注册，判断依据为邮箱
        boolean exit = userService.isUserExit(user.getEmail());
        if(exit){
            throw new UserServiceException("该用户已存在");
        }
        if(user == null){
            return ResponseEntity.badRequest().build();
        }
        //加密密码
        user.setPassword(userService.encode(user.getPassword()));
        int flag = userService.insertAdmin(user);
        if(flag != 1){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok().build();
    }


}
